import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;

import javax.swing.JOptionPane;

/**
 * Copyright (C) 2013  Arun Lee & Bryce Nagareda
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 *	TimeZone - returns the timezone of given latitude and longitude pair.
 *
 * @author Arun Lee
 * @author briceorbryce
 */
public class TimeZone implements Serializable {
	
	/**Serial version UID*/
	private static final long serialVersionUID = 1L;
	
	/**Offset*/
    String dstOffset;
    /**Raw offset*/
    String rawOffset;
    /**The status*/
    String status;
    /**Time zone name*/
    String timeZoneName;
    /**Time zone id*/
    String timeZoneId;

    /**
     * TimeZone 
     * 
     * @param latitude the user inputted
     * @param longitude the user inputted 
     * @throws MonthDayException thrown if error
     */
    public TimeZone(String latitude, String longitude) throws MonthDayException {

        String baseurl = "https://maps.googleapis.com/maps/api/timezone/";
        String currenturl;
        
        try {
            currenturl = baseurl + "json?location=" + latitude + ',' + longitude + "&timestamp=1331161200&sensor=false";
            URL url = new URL(currenturl);
            URLConnection myURLConnection = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));
     	   
			String inputLine;
			
			while ((inputLine = in.readLine()) != null){
				inputLine = inputLine.replace(",", "");
				inputLine = inputLine.replace("\"", "");
				inputLine = inputLine.replace(":", "");
				String[] temp = inputLine.split("\\s+");
				if (temp.length > 1 && temp[1].equals("dstOffset")){
					this.dstOffset = (temp[2]);
				}
				else if (temp.length > 1 && temp[1].equals("rawOffset")){
					this.rawOffset = (temp[2]);
				}
				else if (temp.length > 1 && temp[1].equals("status")){
					this.status = (temp[2]);
				}
				else if (temp.length > 1 && temp[1].equals("timeZoneId")){
					this.timeZoneId = temp[2];
				}
				else if (temp.length > 1 && temp[1].equals("timeZoneName")){
					this.timeZoneName = temp[2] + ' ' + temp [3] + ' ' + temp[4];
				}
			}
			in.close();
            
        }
        catch (UnknownHostException fail) {
        	// gets thrown when there isn't an internet connection
        	JOptionPane.showMessageDialog(null, "Are you connected to the internet?\nValues may be incorrect if you do not have an internet connection.");
        }
        catch (Exception e) {
        	throw new MonthDayException("Invalid value for latitude and longitude \nPlease double check");
        }

    }
    
/**
 * Returns the offset from UTC in seconds.
 * 
 * @return offset from UTC in seconds
 */
    public double getRawOffset() {
        double raw = -1;
        try {
            raw = Double.parseDouble(this.rawOffset);
        } catch (Exception e) {
            //Should check that we have a value for raw offset before calling.
        	// I'm not going to put a check for this. If it fails oh well,
        	// someone should invest in a freakin' watch or a phone.
        	JOptionPane.showMessageDialog(null, "There was a problem with the raw offset.");
        }
        return raw;
    }

    /**
     * Getter for the timezone name.
     * @return the timezone name.
     */
    public String getTimeZoneName() {
        return this.timeZoneName;
    }

    /**
     * Getter for the timezone id.
     * @return timezone id
     */
    public String getTimeZoneId() {
        return this.timeZoneId;
    }
    
    /**
     * Simple test
     * @param args not used
     */
    public static void main(String[] args){
    	TimeZone tz;
		try {
			tz = new TimeZone("21.35", "-1157.89");
			if(tz.getTimeZoneName() == null){
	    		System.out.println("null");
	    	}
	    	System.out.println(tz.getTimeZoneName());
		} catch (MonthDayException e) {
			e.printStackTrace();
		}
    	
    }
}